package parser;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;

import org.apache.commons.compress.archivers.ArchiveException;

import DBside.CDBox;
import DBside.JDBCConnection;
import DBside.Tools;
import DBside.JDBCConnection.Genres;
import LogicSide.Session;

import entities.CD;
import entities.Track;

public class UpdateByFolder {

	/**
	 * @param args
	 *            recieves a path to a folder. tries to parse every file with no
	 *            extension in this folder, if found tar.bz2 extract and parse
	 *            every file
	 */
	private static List<CD> parsed_cds;
	private static String folder_path;
	private static String s;
	private static String full_path;

	public static void main(String[] args) throws IOException, ArchiveException {
		if (args[0] != null) {
			folder_path = args[0];
			full_path = args[0];
		}
		parsed_cds = new ArrayList<CD>();
		File folder = new File(folder_path);
		if (!folder.isDirectory()) {// try to parse
			file_read(folder);
		} else
			folder_read(folder);
		// for(CD cd:parsed_cds)
		// System.out.println(cd);
		System.out.println("parsed files: " + parsed_cds.size());

		JDBCConnection session = new JDBCConnection();
		session.openConnection(Tools.LocalURL, Tools.LocaluserName,
				Tools.Localpassword);
		// session.deleteAll();
		// TODO: parser should preapre a CDBox
		// this is what I did for now:
		CDBox box = new CDBox();
		int i = 0;
		long x = System.currentTimeMillis();
		for (CD cd : parsed_cds) {
			i++;
			if (i % 300 == 0) {

				/*
				 * System.out.println("*********"); for(CD mycd : box.getCds()){
				 * for(ArrayList<Track> tracks : mycd.getTracksMap().values()){
				 * for(Track track : tracks){
				 * System.out.println(track.getSong().getName()); } } }
				 * System.out.println("*********");
				 */
				session.addToBatch(box);
				session.executeBatch();
				System.out.println("so far time: "
						+ (System.currentTimeMillis() - x) / 1000.0);
				box = new CDBox();
			}
			// if(cd!=null)
			// System.out.println(cd);
			box.addCD(cd);
		}
		session.addToBatch(box);
		session.executeBatch();
		System.out.println("parsed: " + parsed_cds.size());
		// System.out.println(box.getArtists().keySet());
		// session.execute("test",
		// "INSERT INTO Album (name, year,freeDBId) VALUES ('dfdsf', 1945, 'dfdf3')");
		// session.deleteAll();
		System.out.println("total time: " + (System.currentTimeMillis() - x)
				/ 1000.0);
		session.closeConnection();
	}

	public static void folder_read(File folder) throws IOException,
			ArchiveException {
		File cur_file;
		for (String f : folder.list()) {

			if (System.getProperty("os.name").toLowerCase().contains("windows"))
				s = "\\";
			else
				s = "/";
			cur_file = new File(folder.getPath() + s + f);
			if (cur_file.isDirectory())
				folder_read(cur_file);
			else if (isTarBz2(cur_file)) {

				parsed_cds.addAll(UpdateByFile.excecute(cur_file.getPath()));

			} else {

				if (cur_file.getName().split("\\.")[0].equals(cur_file
						.getName()))
					file_read(cur_file);
			}
		}

	}

	public static void file_read(File file) throws IOException,
			ArchiveException {
		CD cd;
		if (isTarBz2(file)) {
			parsed_cds.addAll(UpdateByFile.excecute(file.getPath()));
		}

		else {
			InputStream file_stream = new FileInputStream(
					file.getAbsolutePath());
			cd = Parser.parseCD(file_stream);
			if (cd != null) {
				String main_gen_name;
				if (System.getProperty("os.name").toLowerCase()
						.contains("windows"))
					main_gen_name = file.getAbsolutePath().toString()
							.split("\\\\")[file.getAbsolutePath().split("\\\\").length - 2];
				else
					main_gen_name = file.getAbsolutePath().toString().split(s)[file
							.getAbsolutePath().split(s).length - 2];
				boolean found_parent = false;

				for (Genres g : Genres.values())
					if (main_gen_name.equals(g.getName())) {
						found_parent = true;
						cd.setMainGenre(g);
					}
				if (!found_parent) {
					cd.setMainGenre(Genres.NOTSUPPORTED);
				}
				parsed_cds.add(cd);
				// System.out.println(cd);
			}
		}

	}

	private static boolean isTarBz2(File file) {
		String name = file.getName();
		String[] sp = name.split("\\.");
		if (sp.length >= 2)
			if (sp[sp.length - 2].equals("tar"))
				if (sp[sp.length - 1].equals("bz2"))
					return true;
		return false;
	}

	public static void fileToDatabase(String path, Session session1) throws IOException, ArchiveException {
		JDBCConnection session = session1.getCon();
		folder_path = path;
		full_path = path;

		parsed_cds = new ArrayList<CD>();
		File folder = new File(folder_path);
		if (!folder.isDirectory()) {// try to parse
			
				file_read(folder);
			
		} else
			
				folder_read(folder);
			
		// for(CD cd:parsed_cds)
		// System.out.println(cd);
		System.out.println("parsed files: " + parsed_cds.size());
		// session.deleteAll();
		// TODO: parser should prepare a CDBox
		// this is what I did for now:
		CDBox box = new CDBox();
		int i = 0;
		long x = System.currentTimeMillis();
		for (CD cd : parsed_cds) {
			i++;
			if (i % 300 == 0) {

				/*
				 * System.out.println("*********"); for(CD mycd : box.getCds()){
				 * for(ArrayList<Track> tracks : mycd.getTracksMap().values()){
				 * for(Track track : tracks){
				 * System.out.println(track.getSong().getName()); } } }
				 * System.out.println("*********");
				 */
				session.addToBatch(box);
				session.executeBatch();
				System.out.println("so far time: "
						+ (System.currentTimeMillis() - x) / 1000.0);
				box = new CDBox();
			}
			// if(cd!=null)
			// System.out.println(cd);
			box.addCD(cd);
		}
		session.addToBatch(box);
		session.executeBatch();
		System.out.println("parsed: " + parsed_cds.size());
		// System.out.println(box.getArtists().keySet());
		// session.execute("test",
		// "INSERT INTO Album (name, year,freeDBId) VALUES ('dfdsf', 1945, 'dfdf3')");
		// session.deleteAll();
		System.out.println("total time: " + (System.currentTimeMillis() - x)
				/ 1000.0);
		session.closeConnection();
	}
}